//购物车接口
var express = require('express');
var router = express.Router();
// 导入连接数据库key
const pool = require('../MySQLkey/kry');
// 导入工具类
const tools = require('../tool/tool');

/* GET shopping_cart listing. *///通过user_id查询数据
router.get('/:user_id', async function(req, res) {
let connection;
try {
  connection = await pool.getConnection();
  // execute 将在内部调用 prepare 和 query
  const [results, fields] = await connection.execute(
    'SELECT * FROM `shopping_cart` WHERE `user_id`=?',
    [req.params.user_id]
  );

  console.log(results); // 结果集
  //console.log(fields); // 额外的元数据（如果有的话）
  res.send(results);
} catch (err) {
  console.log(err);
}
});
/* POST add to shopping_cart. */
router.post('/', async function(req, res) {
let connection;
try {
  connection = await pool.getConnection();

  const { user_id, product_id, product_specs, quantity = 1 } = req.body;

  // 验证必填字段
  if (!tools.validateUserId(user_id)) {
    return res.status(400).json({
      success: false,
      error: '请提供有效的用户ID'
    });
  }

  if (!tools.validateUserId(product_id)) {
    return res.status(400).json({
      success: false,
      error: '请提供有效的商品ID'
    });
  }

  if (!quantity || quantity < 1) {
    return res.status(400).json({
      success: false,
      error: '商品数量必须大于0'
    });
  }

  // 验证用户是否存在
  const [userExists] = await connection.execute(
    'SELECT id FROM users WHERE id = ? AND status != 0',
    [user_id]
  );

  if (userExists.length === 0) {
    return res.status(404).json({
      success: false,
      error: '用户不存在或已被删除'
    });
  }

  // 验证商品是否存在
  const [productExists] = await connection.execute(
    'SELECT id, name, price FROM products WHERE id = ?',
    [product_id]
  );

  if (productExists.length === 0) {
    return res.status(404).json({
      success: false,
      error: '商品不存在'
    });
  }

  // 开始事务
  await connection.beginTransaction();

  try {
    // 检查购物车中是否已存在相同商品和规格
    const specsJson = product_specs ? JSON.stringify(product_specs) : null;
    const [existingItem] = await connection.execute(
      'SELECT id, quantity FROM shopping_cart WHERE user_id = ? AND product_id = ? AND (product_specs IS NULL AND ? IS NULL OR JSON_EXTRACT(product_specs, "$") = JSON_EXTRACT(?, "$"))',
      [user_id, product_id, specsJson, specsJson]
    );

    if (existingItem.length > 0) {
      // 如果已存在，更新数量
      const newQuantity = existingItem[0].quantity + parseInt(quantity);
      await connection.execute(
        'UPDATE shopping_cart SET quantity = ?, updated_at = NOW() WHERE id = ?',
        [newQuantity, existingItem[0].id]
      );

      await connection.commit();

      tools.handleSuccess(res, {
        cartItemId: existingItem[0].id,
        action: 'updated',
        oldQuantity: existingItem[0].quantity,
        newQuantity: newQuantity,
        addedQuantity: parseInt(quantity)
      }, '购物车商品数量已更新');

    } else {
      // 如果不存在，添加新记录
      const [insertResult] = await connection.execute(
        'INSERT INTO shopping_cart (user_id, product_id, product_specs, quantity, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())',
        [user_id, product_id, specsJson, parseInt(quantity)]
      );

      await connection.commit();

      tools.handleSuccess(res, {
        cartItemId: insertResult.insertId,
        action: 'added',
        user_id: user_id,
        product_id: product_id,
        product_name: productExists[0].name,
        quantity: parseInt(quantity)
      }, '商品已添加到购物车', 200);
    }

  } catch (err) {
    await connection.rollback();
    throw err;
  }

} catch (err) {
  tools.handleError(res, err, '添加到购物车失败');
} finally {
  if (connection) connection.release();
}
});
/* DELETE remove from shopping_cart. */
//删除购物车项
router.delete('/:id', async function(req, res) {
  let connection;
  try {
    connection = await pool.getConnection();

    const cartItemId = req.params.id;

    // 验证购物车项ID
    if (!tools.validateUserId(cartItemId)) {
      return tools.handleError(res, null, '购物车项ID格式不正确', 400);
    }

    // 先查询购物车项是否存在
    const [checkResult] = await connection.query(
      'SELECT id, user_id, product_id, quantity FROM shopping_cart WHERE id = ?',
      [cartItemId]
    );

    if (checkResult.length === 0) {
      return tools.handleError(res, null, '购物车项不存在', 404);
    }

    const cartItem = checkResult[0];

    // 执行删除操作
    const [deleteResult] = await connection.query(
      'DELETE FROM shopping_cart WHERE id = ?',
      [cartItemId]
    );

    // 检查删除是否成功
    if (deleteResult.affectedRows === 0) {
      return tools.handleError(res, null, '删除失败，购物车项不存在', 404);
    }

    // 返回成功结果
    tools.handleSuccess(res, {
      deleted_item: {
        id: parseInt(cartItemId),
        user_id: cartItem.user_id,
        product_id: cartItem.product_id,
        quantity: cartItem.quantity
      },
      affected_rows: deleteResult.affectedRows
    }, '购物车项删除成功');

  } catch (err) {
    tools.handleError(res, err, '删除购物车项失败');
  } finally {
    if (connection) connection.release();
  }
});
/* PUT update shopping_cart. */
router.put('/:id', async function(req, res) {
  //修改quantity
  let connection;
  try {
    connection = await pool.getConnection();  
    const { quantity } = req.body;
    if (!quantity || quantity < 1) {
      return res.status(400).json({
        success: false, 
        error: '商品数量必须大于0'
      });


    }
    const [results, fields] = await connection.execute(
      'UPDATE `shopping_cart` SET `quantity`=?, `updated_at`=NOW() WHERE `id`=?',
      [quantity, req.params.id]
    );
    console.log(results); // 结果集
    console.log(fields); // 额外的元数据（如果有的话）
    res.send(results);
    


  } catch (err) {
    console.log(err);
  }
 
});


module.exports = router;
